package com.xyxy.platform.website.car.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyxy.platform.modules.core.utils.DateUtil;
import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.bind.annotation.CurrentUser;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import com.xyxy.platform.modules.entity.CartDetail;
import com.xyxy.platform.modules.entity.member.Member;
import com.xyxy.platform.modules.entity.trade.Cart;
import com.xyxy.platform.modules.entity.trade.CategoryExample;
import com.xyxy.platform.modules.entity.trade.Goods;
import com.xyxy.platform.modules.entity.trade.OrderInfo;
import com.xyxy.platform.modules.entity.trade.UserAddress;
import com.xyxy.platform.modules.service.common.address.AddressService;
import com.xyxy.platform.modules.service.member.MemberService;
import com.xyxy.platform.modules.service.member.vo.MemberDetail;
import com.xyxy.platform.modules.service.trade.*;
import com.xyxy.platform.modules.service.trade.vo.Order;
import com.xyxy.platform.website.common.vo.CurrentLoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/car")
public class ShopCarController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private CartService cartService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SysAreaService sysAreaService;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, HttpServletResponse response, Model model,@CurrentUser CurrentLoginUser user) {
    	
        List<Cart> carlist = cartService.selectCartByMemberId(user.getId());
        List<CartDetail> list = new ArrayList<CartDetail>();
        double allPrice = 0.0;
        for (Iterator iterator = carlist.iterator(); iterator.hasNext(); ) {
        	OrderInfo order = new OrderInfo();
            CartDetail cd = new CartDetail();
            Cart cart = (Cart) iterator.next();
            cd.setNum(cart.getNumber());
            MemberDetail member = memberService.findMemberDetailById(cart.getMemberId());
            if (member.getImageItemList() != null) {
                cd.setImg(member.getImageItemList().get(0).getUri());
            }
            cd.setUsername(member.getMember().getRealName());
            List<Goods> goodslist = goodsService.selectByGoodsId(cart.getGoodsId()).getList();
            cd.setGoodInfo(goodslist.get(0).getGoodsBrief());
            cd.setPrice(goodslist.get(0).getShopPrice());
            BigDecimal totalPrice = (goodslist.get(0).getShopPrice()).multiply(BigDecimal.valueOf(cart.getNumber()));
            allPrice += totalPrice.doubleValue();
            cd.setTotalPrice(totalPrice);
            cd.setId(cart.getCartId());
            list.add(cd);

        }
        model.addAttribute("carlist", list);
        model.addAttribute("allPrice", allPrice);

        return "car/shopCar";
    }

    /**
     * 查询分页数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "pagination/data", method = RequestMethod.GET)
    public ResponseMessage<?> paginationData(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "1") Integer pageSize,
            String categoryName, Model model
    ) {
        PageHelper.startPage(0 + 1, 1);
        CategoryExample sql = new CategoryExample();
        List<Cart> carlist = cartService.selectCartByMemberId(1);
        List<CartDetail> list = new ArrayList<CartDetail>();
        for (Iterator iterator = carlist.iterator(); iterator.hasNext(); ) {
            CartDetail cd = new CartDetail();
            Cart cart = (Cart) iterator.next();
            cd.setNum(cart.getNumber());
            MemberDetail member = memberService.findMemberDetailById(cart.getMemberId());
            if (null != member.getImageItemList()) {
                cd.setImg(member.getImageItemList().get(0).getUri());
            }
            cd.setUsername(member.getMember().getAlias());
            List<Goods> goodslist = goodsService.selectByGoodsId(cart.getGoodsId()).getList();
            cd.setGoodInfo(goodslist.get(0).getGoodsBrief());
            cd.setPrice(goodslist.get(0).getShopPrice());
            BigDecimal totalPrice = (goodslist.get(0).getShopPrice()).multiply(BigDecimal.valueOf(cart.getNumber()));
            cd.setTotalPrice(totalPrice);
            list.add(cd);
        }
        model.addAttribute("carlist", list);
        PageInfo<CartDetail> pageInfo = new PageInfo<>(list);
        return ResponseUtils.jsonSuccess(pageInfo, "分页查询数据成功!");
    }

    @RequestMapping(value = "/confirm")
    public String confirm(HttpServletRequest request, HttpServletResponse response, Model model,@CurrentUser CurrentLoginUser user) {
        @SuppressWarnings("rawtypes")
        List list = addressService.getListProvince();
        model.addAttribute("provincelist", list);
        String ids = request.getParameter("ids");//商品id
        List<Cart> carlist = new ArrayList<Cart>();
        String[] args = ids.split("_");
        for (int i = 0; i < args.length; i++) {
            Cart cart = new Cart();
            cart = cartService.selectCartByCartId(Long.valueOf(args[i]));
            carlist.add(cart);
        }
        List<CartDetail> cardetaillist = new ArrayList<CartDetail>();
        //BigDecimal allPrice = new BigDecimal(0);
        double allPrice =0.0;
        List<Order> orderlist = new ArrayList<>();

        //加入购物车
        for (Iterator iterator = carlist.iterator(); iterator.hasNext(); ) {
            CartDetail cd = new CartDetail();
            Cart cart = (Cart) iterator.next();
            if(cart!=null){  
	            cd.setNum(cart.getNumber());
	            MemberDetail memberDetail = memberService.findMemberDetailById(user.getId());
	            if (null != memberDetail.getImageItemList()) {
	                cd.setImg(memberDetail.getImageItemList().get(0).getUri());
	            }
	            cd.setUsername(memberDetail.getMember().getRealName());
	            List<Goods> goodslist = goodsService.selectByGoodsId(cart.getGoodsId()).getList();
	            Goods goods = goodslist.get(0);

	            cd.setGoodInfo(goods.getGoodsBrief());
	            cd.setPrice(goods.getShopPrice());
	            BigDecimal totalPrice = (goods.getShopPrice()).multiply(BigDecimal.valueOf(cart.getNumber()));
	            allPrice+=totalPrice.doubleValue();
	            cd.setTotalPrice(totalPrice);
	            cardetaillist.add(cd);
	            MemberDetail md = memberService.findMemberDetailById(cart.getMemberId());
	            Member member = md.getMember();
	            
	            Order order = new Order();
	            //order.setAddressId(Long.valueOf(address));
	            order.setAlias(member.getAlias());
	            order.setGender(member.getGender());
	            order.setGoodName(goods.getGoodsName());
	            order.setGoodPrice(goods.getShopPrice().toString());
	            order.setGoodUnit(goods.getGoodsCompanyNote());
	            if (null != md.getImageItemList()) {
	                order.setImgurl(md.getImageItemList().get(0).getUri());
	            }
	            order.setMemberid(user.getId());
	            order.setNumber(cart.getNumber());
	            String orderSN = "xyxy_"+new Date().getTime();
	            order.setOrderSn(orderSN);
	            order.setOrderTime("");
	            order.setStatus(1);
	            order.setTime(new Date());
	            order.setGoods(goods);
	            order.setPostscript("111"); 
	            order.setPayStatus(0);
	            order.setGoods(goods);
	            orderlist.add(order);
	        	order.setReferer("car");
	            orderService.submitOrderInfo(order);
            }
        }

        model.addAttribute("allPrice", allPrice);
        
        model.addAttribute("cardetaillist", cardetaillist);
        model.addAttribute("ids", ids);
        String addressId = request.getParameter("addressId");
        List<UserAddress> lst = userAddressService.selectAddressById(user.getId());

        for (Iterator iterator = lst.iterator(); iterator.hasNext(); ) {
            UserAddress userAddress = (UserAddress) iterator.next();
            String addressAll = "";
            String proName = "";
            String cityName = "";
            String districtName = "";
            addressAll = addressService.getAddressStr(userAddress.getDistrict().intValue(), 3, "_");
            String[] arg = addressAll.split("_");
            proName = arg[0];
            cityName = arg[1];
            districtName = arg[2];
            userAddress.setProvinceName(proName);
            userAddress.setCityName(cityName);
            userAddress.setDistrictName(districtName);
            if(userAddress.getIsDefault()==1){
            	 model.addAttribute("addressId1", userAddress.getAddressId());
            }
        }
        model.addAttribute("addresslst", lst);
        return "car/confirm";
    }


    @RequestMapping(value = "/saveAddress")
    public String saveAddress(HttpServletRequest request, HttpServletResponse response, Model model,@CurrentUser CurrentLoginUser user) {
        String realname = request.getParameter("consignee");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String area = request.getParameter("district");
        String address = request.getParameter("address");
        String mobile = request.getParameter("mobile");
        String isDefault = request.getParameter("isdefault");
        UserAddress uaddr = new UserAddress();
        uaddr.setAddress(address);
        uaddr.setCity(Long.valueOf(city));
        uaddr.setConsignee(realname);
        uaddr.setDistrict(Long.valueOf(area));
        uaddr.setEmial("");
        uaddr.setMemberId(user.getId());
        uaddr.setMobile(mobile);
        uaddr.setProvince(Long.valueOf(province));
        uaddr.setTel("");
        if (null != isDefault) {
            uaddr.setIsDefault(Integer.valueOf(isDefault));
        }
        uaddr.setCreateTime(new Date());
        String addressId = request.getParameter("addressId");
        String ids = request.getParameter("ids");
        List<UserAddress> list = userAddressService.selectAddressById(user.getId());
        if (addressId != null) {
            uaddr.setAddressId(Long.valueOf(addressId));
            userAddressService.editUserAddress(uaddr);
        } else {
        	if(StringUtils.equals(isDefault, "1")){
        		if(list !=null){
	        		for (UserAddress userAddress : list) {
	        	        userAddress.setIsDefault(0);
	        	        userAddress.setAddressId(userAddress.getAddressId());
		        		userAddressService.editUserAddress(userAddress);
					}
        		}
                userAddressService.insertUserAddress(uaddr);       			
        	} else{
        		uaddr.setIsDefault(0);
                userAddressService.insertUserAddress(uaddr);       			
        	}		
        }
        return "redirect:/car/confirm?ids=" + ids + "&addressId=" + addressId;
    }

    @ResponseBody
    @RequestMapping(value = "/getCityByProvinceId/{id}", method = RequestMethod.GET)
    public ResponseMessage<?> getCityByProvinceId(Model model, @PathVariable("id") String id) {
        List list = addressService.getListCity(Integer.valueOf(id));
        return ResponseUtils.jsonResult(list, true, "success");
    }


    @ResponseBody
    @RequestMapping(value = "/getAddressById/{id}", method = RequestMethod.GET)
    public ResponseMessage<?> getAddressById(Model model, @PathVariable("id") String id) {
        UserAddress bean = userAddressService.selectByPrimaryKey(StringUtils.isEmpty(id) ? 0 : Long.valueOf(id));
        List<UserAddress> list = new ArrayList<UserAddress>();
        list.add(bean);
        return ResponseUtils.jsonResult(list, true, "success");
    }

    @RequestMapping(value = "/deleteCart")
    public String deleteCartByid(HttpServletRequest request, HttpServletResponse response, Model model) {
        String id = request.getParameter("id");
        String[] args = id.split("_");
        for (int i = 0; i < args.length; i++) {
            cartService.deletebyId(Long.valueOf(args[i]));
        }
        return "redirect:/car/index";
    }


    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("id") String id) {
        String ids = request.getParameter("ids");
        userAddressService.deleteByPrimaryKey(Long.valueOf(id));
        return "redirect:/car/confirm?ids=" + ids;
    }

    @ResponseBody
    @RequestMapping(value = "/getAreaByCityId/{id}", method = RequestMethod.GET)
    public ResponseMessage<?> getAreaByCityId(Model model, @PathVariable("id") String id) {
        List list = addressService.getListArea(Integer.valueOf(id));
        return ResponseUtils.jsonResult(list, true, "success");
    }

    @RequestMapping(value = "/delete")
    public String delete(HttpServletRequest arg0, HttpServletResponse arg1) {
        String addrId = arg0.getParameter("id");
        int del = userAddressService.deleteByPrimaryKey(Long.valueOf(addrId));
        return "car/confirm";
    }

    @RequestMapping(value = "/payment")
    public String payment(HttpServletRequest arg0, HttpServletResponse arg1, Model model,@CurrentUser CurrentLoginUser user) {
        String ids = arg0.getParameter("ids");
        String remarks = arg0.getParameter("message");
        String address = arg0.getParameter("addressId");
        UserAddress useradd = userAddressService.selectByPrimaryKey(Long.valueOf(address));
        model.addAttribute("address", useradd.getAddress());
        model.addAttribute("mobile", useradd.getMobile());
        model.addAttribute("consignee", useradd.getConsignee());
        String[] args = ids.split("_");
        List<Order> list = new ArrayList<>();
        double price = 0;
        for (int i = 0; i < args.length; i++) {
            Cart cart = new Cart();
            cart = cartService.selectCartByCartId(Long.valueOf(args[i]));
            List<Goods> goodslist = goodsService.selectByGoodsId(cart.getGoodsId()).getList();
            Goods goods = goodslist.get(0);
            MemberDetail md = memberService.findMemberDetailById(cart.getMemberId());
            Member member = md.getMember();
            BigDecimal totalPrice = (goods.getShopPrice()).multiply(BigDecimal.valueOf(cart.getNumber()));
            price+=totalPrice.doubleValue();
            cartService.deletebyId(cart.getCartId());        
        }
        List<OrderInfo>  orderlist = orderService.getMemberOrder(user.getId(),null, "car");
        for (OrderInfo orderInfo2 : orderlist) {
        	orderInfo2.setOrderStatus(2);
        	orderInfo2.setPayStatus(2);
        	orderService.updateOrderInfo(orderInfo2);
		}
        model.addAttribute("totalPrice", price);
        String prov = sysAreaService.getSysAreaById(useradd.getProvince()).getAreaname();
        String city = sysAreaService.getSysAreaById(useradd.getCity()).getAreaname();
        String district = sysAreaService.getSysAreaById(useradd.getDistrict()).getAreaname();

        model.addAttribute("prov", prov);
        model.addAttribute("city", city);
        model.addAttribute("district", district);
        model.addAttribute("ids", ids);
        model.addAttribute("addressId", address);
        return "car/payment";
    }

    @RequestMapping(value = "/paysuccess")
    public String paysuccess(HttpServletRequest arg0, HttpServletResponse arg1, Model model,@CurrentUser CurrentLoginUser user) {
        String ids = arg0.getParameter("ids");
        String ordersn = arg0.getParameter("ordersn");
        String address = arg0.getParameter("addressId");
        UserAddress useradd = userAddressService.selectByPrimaryKey(Long.valueOf(address));
        model.addAttribute("address", useradd.getAddress());
        model.addAttribute("mobile", useradd.getMobile());
        model.addAttribute("consignee", useradd.getConsignee());
        String[] args = ids.split("_");
        List<Order> list = new ArrayList<>();
        String orderSN = new Date().getTime() + "";
        double price = 0;
        /*for (int i = 0; i < args.length; i++) {
            Cart cart = new Cart();
            cart = cartService.selectCartByCartId(Long.valueOf(args[i]));
            List<Goods> goodslist = goodsService.selectByGoodsId(cart.getGoodsId()).getList();
            Goods goods = goodslist.get(0);
            price += goods.getShopPrice().doubleValue() * cart.getNumber();
        }*/
        List<OrderInfo>  orderlist = orderService.getMemberOrder(user.getId(),null, "car");
        for (OrderInfo orderInfo2 : orderlist) {
        	orderInfo2.setOrderStatus(3);
        	orderInfo2.setPayStatus(2);
        	orderService.updateOrderInfo(orderInfo2);
		}
        model.addAttribute("totalPrice", price);
        model.addAttribute("orderSN", orderSN);
        String prov = sysAreaService.getSysAreaById(useradd.getProvince()).getAreaname();
        String city = sysAreaService.getSysAreaById(useradd.getCity()).getAreaname();
        String district = sysAreaService.getSysAreaById(useradd.getDistrict()).getAreaname();

        model.addAttribute("ordersn", ordersn);
        model.addAttribute("prov", prov);
        model.addAttribute("city", city);
        model.addAttribute("district", district);
        return "car/paysuccess";
    }

    /**
     * 添加至购物车
     * @param user 当前登录用户
     * @param goodsId 服务ID
     * @param serverDate 服务日期
     * @param serverTimeIdx 服务时间标记
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ResponseMessage<?> addGoodsToCart(
            @CurrentUser CurrentLoginUser user,
            @RequestParam Long goodsId,
            @RequestParam Long serverDate,
            @RequestParam Integer serverTimeIdx
    ) {
        Cart cart = new Cart();
        cart.setMemberId(user.getId());
        cart.setGoodsId(goodsId);

        JSONObject contentJsonObject = new JSONObject();
        contentJsonObject.put("serverDate", serverDate);
        contentJsonObject.put("serverTimeIdx", serverTimeIdx);
        cart.setGoodscontent(contentJsonObject.toJSONString());

        if (cartService.insert(cart)) {
            return ResponseUtils.jsonSuccess(null, "添加服务至购物车成功!");
        }
        return ResponseUtils.jsonFail(null, "添加服务至购物车失败!");
    }
}
